<template>
  <p-card :bordered="false">
    <!-- 查询区域 -->
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <p-form layout="inline" @keyup.enter.native="searchQuery">
        <p-row :gutter="24">

        </p-row>
      </p-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <p-button @click="handleAdd" v-if="userInfo.uid==='division_manage'" type="primary" icon="plus">新增</p-button>
      <p-button @click="batchDel" v-if="userInfo.uid==='division_manage'" type="danger" icon="delete"> 删除</p-button>
      <!-- <p-button  @click="sumitHandle" type="primary">提交</p-button> -->
      <p-button v-if=" userInfo.uid==='life_manage'&&selectionRows[0]&&selectionRows[0].status === 5" @click="approvehandle" type="primary">确认</p-button>
      <p-button v-if=" userInfo.uid==='life_manage'&&selectionRows[0]&&selectionRows[0].status === 5" @click="lifeManageBack" type="primary">退回</p-button>
   
      <p-badge v-if="userInfo.uid==='division_manage'" :count="taskCount" show-zero style="margin-right:10px;">
        <p-button @click="toProcess" type="primary">审核流程</p-button>
      </p-badge>

      <template v-if="cgButtonList && cgButtonList.length>0" v-for="(item,index) in cgButtonList">
          <p-button
            v-if=" item.optType=='js' && (item.groupTag == null || item.groupTag == '' )"
            :key=" 'cgbtn'+index "
            @click="cgButtonJsHandler(item.buttonCode)"
            type="primary"
            :icon="item.buttonIcon"
          >{{ item.buttonName }}</p-button>
          <p-button
            v-else-if=" item.optType=='action' && (item.groupTag == null || item.groupTag == '' )"
            :key=" 'cgbtn'+index "
            @click="cgButtonActionHandler(item.buttonCode)"
            type="primary"
            :icon="item.buttonIcon"
          >{{ item.buttonName }}</p-button>
      </template>

        <!-- 高级查询区域 -->
        <j-super-query :fieldList="fieldList" ref="superQueryModal" @handleSuperQuery="handleSuperQuery"></j-super-query>

        <!-- <p-dropdown v-if="selectedRowKeys.length > 0">
        <p-menu slot="overlay">
          <p-menu-item key="1" @click="batchDel">
            <p-icon type="delete" />删除
          </p-menu-item>
        </p-menu>
        <p-button style="margin-left: 8px">
          批量操作
          <p-icon type="down" />
        </p-button>
      </p-dropdown> -->

      <p-dropdown  v-for="(item,index) in groupTag" :key="index">
        <p-button >
          {{item.name}}
          <p-icon type="down" />
        </p-button>
          <p-menu slot="overlay"  >
            <template  v-for="(items,indexs) in item.data">
              <p-menu-item v-if=" items.optType=='js' " :key="indexs" @click="cgButtonJsHandler(items.buttonCode)">
                <p-icon :type="items.buttonIcon" />{{items.buttonName}}
              </p-menu-item>
              <p-menu-item v-else-if=" items.optType=='action' " :key="indexs" @click="cgButtonActionHandler(items.buttonCode)">
                <p-icon :type="items.buttonIcon" />{{items.buttonName}}
              </p-menu-item>
            </template>
          </p-menu>
      </p-dropdown>

    </div>
    <!-- table区域-begin -->
    <div>
        <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
            <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
            <a style="margin-left: 24px" @click="onClearSelected">清空</a>

            <span style="float:right;">
              <a @click="handleExportXls('科研加工申请单')"><p-icon type="download" />导出</a>
                 <p-divider type="vertical" />
              <p-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="importExcelUrl" @change="handleImportExcel">
                 <a><p-icon type="import" />导入</a>
              </p-upload>
              <p-divider type="vertical" />
              <a @click="initDataList()"><p-icon type="sync" />刷新</a>
              <p-divider type="vertical" />
                <p-popover title="自定义列" trigger="click" placement="leftBottom"  :overlay-style="getWidth">
                <template slot="content">
                  <p-checkbox-group @change="onColSettingsChange" v-model="settingColumns" :defaultValue="settingColumns">
                    <p-row>
                      <template v-for="(item,index) in defColumns">
                        <template v-if="item.key!='rowIndex'&& item.dataIndex!='action'">
                            <p-col :span="12"><p-checkbox :value="item.dataIndex">{{ item.title }}</p-checkbox></p-col>
                        </template>
                      </template>
                    </p-row>
                  </p-checkbox-group>
                </template>
                <a><p-icon type="setting" />自定义列</a>
              </p-popover>
            </span>
        </div>


      <p-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :columns="columns"
        :scroll="tableScroll"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange, type:'checkbox'}"
        :customRow="clickThenSelect"
        @change="handleTableChange">

            <template slot="scientificType" slot-scope="text">
              <span>{{text === '1'?'单盘贴片外协加工':'厂内科研工单'}}</span>
            </template>
            <template slot="htmlSlot" slot-scope="text">
              <div v-html="text"></div>
            </template>
            <template slot="imgSlot" slot-scope="text">
              <span v-if="!text" style="font-size: 12px;font-style: italic;">无此图片</span>
              <img v-else :src="getImgView(text)" height="25px" alt="图片不存在" style="max-width:80px;font-size: 12px;font-style: italic;"/>
            </template>
            <template slot="fileSlot" slot-scope="text">
              <span v-if="!text" style="font-size: 12px;font-style: italic;">无此文件</span>
              <p-button
                v-else
                :ghost="true"
                type="primary"
                icon="download"
                size="small"
                @click="uploadFile(text)">
                下载
              </p-button>
            </template>

            <span slot="action" slot-scope="text, record">
              <a :disabled="record.status===0 && userInfo.uid==='division_manage' ?false:true" @click="handleEdit(record)">编辑</a>
              <p-divider type="vertical" />
              <p-dropdown>
                <a class="ant-dropdown-link">更多 <p-icon type="down" /></a>
                <p-menu slot="overlay">
                  <p-menu-item 
                  v-if="userInfo.uid==='life_manage'?false:
                  userInfo.uid==='division_manage'?false:
                  userInfo.uid==='process_manage'&&record.status>1&&record.status<4?true:
                  userInfo.uid==='pur_manage'&&record.status===4?true:false">
                      <a @click="handleDetSumit(record)">确认</a>
                  </p-menu-item>
                  <p-menu-item>
                      <a @click="handleDetail(record)">详情</a>
                  </p-menu-item>
                  <!-- <p-menu-item>
                      <a @click="handleDelete(record.id)">删除</a>
                  </p-menu-item> -->
                    <template v-if="cgButtonLinkList && cgButtonLinkList.length>0" v-for="(btnItem,btnIndex) in cgButtonLinkList">
                      <p-menu-item :key=" 'cgbtnLink'+btnIndex " v-if="showLinkButton(btnItem,record)">
                        <a href="javascript:void(0);" @click="cgButtonLinkHandler(record,btnItem.buttonCode,btnItem.optType)">
                          <p-icon v-if="btnItem.buttonIcon" :type="btnItem.buttonIcon" />
                          {{ btnItem.buttonName }}
                        </a>
                      </p-menu-item>
                    </template>
                </p-menu>
              </p-dropdown>
            </span>
      </p-table>
    </div>

    <!-- <p-tabs defaultActiveKey="1">
      <p-tab-pane tab="供应商范围建议" key="1" >
        <mes-mf-suggest-list :mainId="newSelectedMainId" />
      </p-tab-pane>
    </p-tabs> -->

    <!-- <mes-mf-route-maintenance ref="modalRoute" :projectId="projectId"></mes-mf-route-maintenance> -->

    <mesMfScientific-modal ref="modalForm" :userInfos="userInfo" :EnhanceJS="EnhanceJS"  @ok="modalFormOk" @closeModal="closeModal"></mesMfScientific-modal>
    
    <mes-mf-scientific-detail-modal ref="modalDetail"></mes-mf-scientific-detail-modal>
     <!-- 弹出窗 -->
     <Fx-compontens-modal @ok="modalFormOk"  ref="modalCompon" :getList="queryInfo" :title="title" :dictOptions="dictOptions"></Fx-compontens-modal>
  </p-card>
</template>

<script>

  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import {api} from '@/api/manage'
  import { mapState } from "vuex";
  import JSuperQuery from '@/components/jeecg/JSuperQuery.vue'
  import { filterObj } from '@/utils/util'
  import MesMfScientificModal from './modules/MesMfScientificModal'
  import MesMfScientificDetailModal from './modules/MesMfScientificDetailModal' 
  import MesMfRouteMaintenance from './modules/MesMfRouteMaintenance'
  import Vue from 'vue'
  import moment from 'moment'
  import MesMfSuggestList from './MesMfSuggestList'
  import {initDictOptions, filterMultiDictText} from '@/components/dict/JDictSelectUtil'
  import ButtonExpHandler from '@/components/jeecgbiz/modules/ButtonExpHandler'
  import { postAction,getAction,deleteAction } from '@/api/manage'
  import FxCompontensModal from "@/components/jeecgbiz/FxCompontensModal"

  //高级查询modal需要参数
    const superQueryFieldList=[
            {
                value:'scientificOrder',
                text: '任务编号',
                type: 'string'
            },
            {
                value:'scientificPlease',
                text: '申请人',
                type: 'select',
                dictCode: ''
            },
            {
                value:'dptno',
                text: '部门名称',
                type: 'select',
                dictCode: ''
            },
            {
                value:'scientificContact',
                text: '联系方式',
                type: 'string'
            },
            {
                value:'scientificno',
                text: '项目编码',
                type: 'string'
            },
            {
                value:'scientificname',
                text: '项目名称',
                type: 'string'
            },
            {
                value:'scientificType',
                text: '加工类型',
                type: 'select',
                dictCode: 'mes_scientific_type'
            },
            {
                value:'name',
                text: '名称',
                type: 'string'
            },
            {
                value:'contentTime',
                text: '需求完成时间',
                type: 'string'
            },
            {
                value:'model',
                text: '型号/图号（版号）',
                type: 'string'
            },
            {
                value:'scientificStarttime',
                text: '计划开始时间',
                type: 'string'
            },
            {
                value:'scientificQitime',
                text: '实际物料齐套时间',
                type: 'string'
            },
            {
                value:'status',
                text: '当前状态',
                type: 'select',
            },
            {
                value:'bomReport',
                text: 'BOMreport',
                type: 'string'
            },
            {
                value:'researchBom',
                text: '科研bom表',
                type: 'string'
            },
            {
                value:'accessory',
                text: '附件',
                type: 'string'
            },
            {
                value:'supno',
                text: '供应商编码',
                type: 'string'
            },
            {
                value:'supname',
                text: '供应商名称',
                type: 'string'
            },
            {
                value:'scientificCompleteTime',
                text: '事业部计划完成时间',
                type: 'Date'
            },
            {
                value:'actualStartTime',
                text: '事业部实际领用开始时间',
                type: 'Date'
            },
            {
                value:'actualFinishTime',
                text: '事业部实际完成时间',
                type: 'Date'
            },
            {
                value:'actualCompletion',
                text: '实际完成情况',
                type: 'select',
                dictCode: 'mes_actual_completion'
            },
            {
                value:'createBy',
                text: '创建人',
                type: 'string'
            },
            {
                value:'createTime',
                text: '创建日期',
                type: 'Date'
            },
            {
                value:'updateBy',
                text: '更新人',
                type: 'string'
            },
            {
                value:'updateTime',
                text: '更新日期',
                type: 'Date'
            },
    ]

  export default {
    name: "MesMfScientificList",
    mixins:[JeecgListMixin],
    components: {
      JSuperQuery,
      MesMfSuggestList,
      FxCompontensModal,
      MesMfScientificModal,
      MesMfRouteMaintenance,
      MesMfScientificDetailModal
    },
    data () {
      return {
        fieldList:superQueryFieldList,
        superQueryFlag:false,
        superQueryParams: '',
        description: '科研加工申请单管理页面',
        EnhanceJS:'',
        cgButtonLinkList:[],
        cgButtonList:[],
        title:'',//存表名
        groupTag:[],
        queryInfo: [],
        code: '',
        // 表头
        columns: [],
         //列设置
         settingColumns:[],
         //列定义
         defColumns: [
          {
            title: '任务编号',
            align: 'center',
            dataIndex: 'scientificOrder',
          },
          {
            title: '申请人',
            align: 'center',
            dataIndex: 'scientificPlease',
          },
          {
            title: '部门名称',
            align: 'center',
            width:200,
            dataIndex: 'dptno',
          },
          {
            title: '联系方式',
            align: 'center',
            dataIndex: 'scientificContact',
          },
          {
            title: '项目编码',
            align: 'center',
            dataIndex: 'scientificno',
          },
          {
            title: '项目名称',
            align: 'center',
            dataIndex: 'scientificname',
          },
          {
            title: '加工类型',
            align: 'center',
            dataIndex: 'scientificType',
            scopedSlots: {customRender: 'scientificType'},
          },
          {
            title: '名称',
            align: 'center',
            dataIndex: 'name',
          },
          {
            title: '需求完成时间',
            align: 'center',
            dataIndex: 'contentTime',
            customRender:(text)=>{
                return text?moment(text).format('YYYY-MM-DD'):'--'
            },
          },
          {
            title: '型号/图号（版号）',
            align: 'center',
            dataIndex: 'model',
          },
          {
            title: '计划开始时间',
            align: 'center',
            dataIndex: 'scientificStarttime',
            customRender:(text)=>{
                return text?moment(text).format('YYYY-MM-DD'):'--'
            },
          },
          {
            title: '实际物料齐套时间',
            align: 'center',
            dataIndex: 'scientificQitime',
            customRender:(text)=>{
                return text?moment(text).format('YYYY-MM-DD'):'--'
            },

          },
          
          {
            title: 'BOMreport',
            align: 'center',
            dataIndex: 'bomReport',
            scopedSlots: {customRender: 'fileSlot'},
          },
          {
            title: '科研bom表',
            align: 'center',
            dataIndex: 'researchBom',
            scopedSlots: {customRender: 'fileSlot'},
          },
          {
            title: '附件',
            align: 'center',
            dataIndex: 'accessory',
            scopedSlots: {customRender: 'fileSlot'},
          },
          {
            title: '事业部计划完成时间',
            align: 'center',
            dataIndex: 'scientificCompleteTime',
            customRender:(text)=>{
                return text?moment(text).format('YYYY-MM-DD'):'--'
            },

          },
          {
            title: '事业部实际领用开始时间',
            align: 'center',
            dataIndex: 'actualStartTime',
            customRender:(text)=>{
                return text?moment(text).format('YYYY-MM-DD'):'--'
            },

          },
          {
            title: '事业部实际完成时间',
            align: 'center',
            dataIndex: 'actualFinishTime',
            customRender:(text)=>{
                return text?moment(text).format('YYYY-MM-DD'):'--'
            },
          },
          {
            title: '实际完成情况',
            align: 'center',
            dataIndex: 'actualCompletion',
          },
          {
            title: '创建人',
            align: 'center',
            dataIndex: 'createBy',
          },
          {
            title: '创建日期',
            align: 'center',
            dataIndex: 'createTime',
            customRender:(text)=>{
                return text?moment(text).format('YYYY-MM-DD'):'--'
            },
          },
          {
            title: '更新人',
            align: 'center',
            dataIndex: 'updateBy',
          },
          {
            title: '更新日期',
            align: 'center',
            dataIndex: 'updateTime',
            customRender:(text)=>{
                return text?moment(text).format('YYYY-MM-DD'):'--'
            },
          },
          // (-1:完成 0:待提交 1:审批中 2:待工艺评审 3:待工艺给出供应商建议 4:待采购评审 5:待需求发布)
          {
            title: '当前状态',
            align: 'center',
            fixed: 'right',
            dataIndex: 'status',
            customRender:(text)=>{
                return text===-1?'完成':text===0?'待提交':text===1?'审批中':text===2?'待工艺评审':
                text===3?'待工艺给出供应商建议':text===4?'待采购评审':text===5?'待需求发布':'需求已发布'
            },
          },
          {
            title: '操作',
            dataIndex: 'action',
            align: 'center',
            fixed: 'right',
            width: 100,
            scopedSlots: { customRender: 'action' },
          }
        ],
        
        url: {
          list: '/mes-manufacture/mfScientific/list',
          delete: '/mes-manufacture/mfScientific/',
          deleteBatch: '/mes-manufacture/mfScientific/',
          exportXlsUrl: '/mes-manufacture/auto/mesMfScientific/exportXls',
          importExcelUrl: '/mes-manufacture/auto/mesMfScientific/importExcel',
          getColumns: '',
          buttonAction: '/mes-manufacture/online/cgform/api/doButton',
          lifeBack:'/mes-manufacture/mfScientific/back/',
          lifeApprove:'/mes-manufacture/mfScientific/approve',//申请
          getTaskCount:'/poros-bpmengine/task/getTaskCount', //待办数量
          userList:'/poros-permission/secStaff/list', //用户列表
          userUid:'/poros-permission/secStaff/getUserByUid/',//uid yonghu
          getCurUser:'/poros-permission/secStaff/getCurUser',
        },
        dictOptions:{
         dptname:[],
         scientificType:[],
         scientificState:[],
         actualCompletion:[],
        },
        /* 分页参数 */
        ipagination:{
          current: 1,
          pageSize: 10,
          pageSizeOptions: ['10', '20', '50'],
          showTotal: (total, range) => {
            return range[0] + "-" + range[1] + " 共" + total + "条"
          },
          showQuickJumper: true,
          showSizeChanger: true,
          total: 0
        },
        selectedMainId:'',
        projectId:'',
        taskCount:0,
        userInfo:{},
        approvalStatus:'',
        user:this.$store.state.user
      }
    },
    computed: {
      importExcelUrl: function(){
        return `${api.test}${this.url.importExcelUrl}`;
      },
      getWidth:function(){
        if(this.defColumns.length > 14){
          return {width : '500px'}
        }
      },
      newSelectedMainId:function(){
        if(typeof(this.selectedMainId) == 'number'){
          return this.selectedMainId.toString()
        }else{
          return this.selectedMainId
        }
      },
			tableScroll(){
			 if(this.columns.length > 10){
					return { x: this.columns.length*150-450 }
				}
      },
      // ...mapState({
      //   userInfo: state => state.user,
      // }),
    },
     created() {
          this.getCurUsers()
          this.initColumns();
          this.setdefColumns();
          this.getTaskCount()
          // this.initDataList()
     },
     mounted(){
     },
    // watch:{
    //   userInfo:{
    //     handler(newVal,oldVal){
    //        this.userInfo = newVal
    //       this.getuserUidList(this.userInfo.uid)
    //     },
    //     deep:true
    //   }
    // },
    methods: {
      //uid 用户
      getuserUidList(uid){
         getAction(this.url.userUid+uid).then(res=>{
            this.userInfo = res.data || {}
             console.log(this.userInfo.uid)
          })
    },
    //当前用户
    getCurUsers(){
      getAction(this.url.getCurUser).then(res=>{
        if(res.code === 0){
          this.userInfo = res.data || {}
          console.log(this.userInfo.uid)
          if(this.userInfo.uid === 'division_manage'){
              this.approvalStatus = '-1,0,1,6'
            }else if(this.userInfo.uid === 'process_manage'){
              this.approvalStatus = '2,3'
            }else if(this.userInfo.uid === 'pur_manage'){
              this.approvalStatus = 4
            }else if(this.userInfo.uid === 'life_manage'){
              this.approvalStatus = 5
            } 
            console.log(this.approvalStatus)
            this.initDataList()
        }
      })
    },
      approvehandle(){
        const info={
          ids:this.selectionRows.map(item=>item.id)
        }
        postAction(this.url.lifeApprove,info).then(res=>{
           if(res.code === 0){
             this.$message.success('操作成功')
             this.initDataList()
           }
        })
      },
      sumitHandle(){

      },
      //生管回退
      lifeManageBack(){
        getAction(this.url.lifeBack+this.selectionRows[0].id).then(res=>{
             if(res.code === 0){
               this.$message.success('操作成功')
               this.initDataList()
             }
        })
      },
      //新增
      handleAdd() {
      this.$refs.modalForm.add()
      // this.$refs.modalForm['getRuleCodeValue'] ? this.$refs.modalForm.getRuleCodeValue() : ''
      this.$refs.modalForm.title = '新增'
      this.$refs.modalForm.disableSubmit = false
    },
    modalFormOk(){
      this.initDataList()
      this.getTaskCount()
    },
      //待办数量
      getTaskCount(){
        const info = {
          definitionKey:'mfsci',
          uid:'' //super_admin
        }
        getAction(this.url.getTaskCount,info).then(res=>{
          if(res.code === 0){
            this.taskCount = res.data || 0
          }
        })
      },

      handleDetSumit(record) {
      this.$refs.modalForm.edit(record,1)
      this.$refs.modalForm.title = '详情'
      this.$refs.modalForm.disableSubmit = true
     },

     handleDetail(record) {
      this.$refs.modalDetail.edit(record,1)
      this.$refs.modalDetail.title = '详情' 
     },
     batchDel: function() {
      if (!this.url.deleteBatch) {
        this.$message.error('请设置url.deleteBatch属性!')
        return
      }
      if (this.selectedRowKeys.length <= 0) {
       return this.$message.warning('请选择一条记录！')
      }
      const eq = this.selectionRows.every(ck=>ck.status===1 || ck.status===0)
      if (!eq) {
       return this.$message.warning('请选择【待提交】【审批中】状态可进行删除！')
      }
      let ids = this.selectedRowKeys.map(item=>item).toString()
      let that = this
      this.$confirm({
        title: '确认删除',
        content: '是否删除选中数据?',
        onOk: function() {
          that.loading = true
          deleteAction(that.url.deleteBatch+ids).then((res) => {
            if (res.success) {
              that.$message.success('操作成功')
              that.initDataList(1)
              that.onClearSelected()
            } else {
              that.$message.warning(res.msg)
            }
          }).finally(() => {
            that.loading = false
          })
        }
      })
    },

      closeModal(data){
        this.projectId = data
        console.log(this.projectId)
        this.$refs.modalRoute.openModal(this.projectId)
      },
      toProcess(){
        this.$router.push({path:'/work/components/MesWaitToDone',query:{definitionKey:'mfsci'}})
      },

      setdefColumns(){
        if(this.columns.length > 13){
          let arrLength = this.columns.length-1
          this.columns.forEach((item,index)=>{
            item["width"] = 150
          })
          this.columns[arrLength]['fixed'] = 'right'
          this.columns[0]['fixed'] = 'left'
          this.columns[1]['fixed'] = 'left'
        }
      },
      initColumns(){
        //权限过滤（列权限控制时打开，修改第二个参数为授权码前缀）
        //this.defColumns = colAuthFilter(this.defColumns,'testdemo:');

        var key = this.$route.name+":colsettings";
        let colSettings= Vue.ls.get(key);
        if(colSettings==null||colSettings==undefined){
          let allSettingColumns = [];
          this.defColumns.forEach(function (item,i,array ) {
            allSettingColumns.push(item.dataIndex);
          })
          this.settingColumns = allSettingColumns;
          this.columns = this.defColumns;
        }else{
          this.settingColumns = colSettings;
          const cols = this.defColumns.filter(item => {
            if(item.key =='rowIndex'|| item.dataIndex=='action'){
              return true;
            }
            if (colSettings.includes(item.dataIndex)) {
              return true;
            }
            return false;
          })
          this.columns =  cols;
        }
      },
      //列设置更改事件
      onColSettingsChange (checkedValues) {
        var key = this.$route.name+":colsettings";
        Vue.ls.set(key, checkedValues, 7 * 24 * 60 * 60 * 1000)
        this.settingColumns = checkedValues;
        const cols = this.defColumns.filter(item => {
          if(item.key =='rowIndex'|| item.dataIndex=='action'){
            return true
          }
          if (this.settingColumns.includes(item.dataIndex)) {
            return true
          }
          return false
        })
        this.columns =  cols;
      },
        //高级查询方法
        handleSuperQuery(arg) {
            if(!arg){
                this.superQueryParams=''
                this.superQueryFlag = false
            }else{
                this.superQueryFlag = true
                this.superQueryParams=JSON.stringify(arg)
            }
            this.initDataList()
        },
        // 获取查询条件
        getQueryParams() {
            let sqp = {}
            if(this.superQueryParams){
                sqp['superQueryParams']=encodeURI(this.superQueryParams)
            }
            var param = Object.assign(sqp, this.queryParam, this.isorter);
            param.field = this.getQueryField();
            param.pageNo = this.ipagination.current;
            param.limit = this.ipagination.pageSize;
            return filterObj(param);
        },
      initDictConfig(){
        initDictOptions('sys_depart,depart_name,id').then((res) => {
          if (res.success) {
            this.$set(this.dictOptions, 'dptname', res.data)
          }
        })
        initDictOptions('mes_scientific_type').then((res) => {
          if (res.success) {
            this.$set(this.dictOptions, 'scientificType', res.data)
          }
        })
        initDictOptions('mes_ba_Scientific').then((res) => {
          if (res.success) {
            this.$set(this.dictOptions, 'scientificState', res.data)
          }
        })
        initDictOptions('mes_actual_completion').then((res) => {
          if (res.success) {
            this.$set(this.dictOptions, 'actualCompletion', res.data)
          }
        })
      },
      clickThenSelect(record) {
        return {
          on: {
            click: () => {
              // this.onSelectChange(record.id.split(","), [record]);
            }
          }
        }
      },
      onClearSelected() {
        this.selectedRowKeys = [];
        this.selectionRows = [];
        this.selectedMainId=''
      },
      onSelectChange(selectedRowKeys, selectionRows) {
        this.selectedMainId=selectedRowKeys[0]
        this.selectedRowKeys = selectedRowKeys;
        this.selectionRows = selectionRows;
        console.log(this.selectionRows)
      },
      initDataList(arg) {
        if(!this.url.list){
          this.$message.error("请设置url.list属性!")
          return
        }
        //加载数据 若传入参数1则加载第一页的内容
        if (arg === 1) {
          this.ipagination.current = 1;
        }
        this.onClearSelected()
        // var params={}
        let params = this.getQueryParams();//查询条件
        let info = {approvalStatus:this.approvalStatus}
        const ect = Object.assign(params,info)
        this.loading = true;
        getAction(this.url.list,info).then((res) => {
          if (res.success) {
            this.dataSource = res.data.records;
            console.log(this.dataSource)
            this.ipagination.total = res.data.total;
          }
          if(res.code===510){
            this.$message.warning(res.msg)
          }
          this.loading = false;
        })
      },

      // 弹出窗组件
      showDemoModal() {
        this.$refs.modalCompon.modalShow();
      },
      //点击btn获取数据
      btnGetData(tableName,title){
        getAction(`${this.url.getColumns}`,{
          tableName:tableName
        }).then(
          res=>{
            if(res.code == 0){
              this.queryInfo = res.data.columns
              this.title = title
              this.dictOptions = res.data.dictOptions
              this.showDemoModal()
            }else{
               this.$message.warning(res.msg);
            }
          }
        )
      },
      //筛选分组
      getGroupTag(arrList) {
        let arr = [];
        var map = {},
            dest = [];
        arrList.forEach((item, index) => {
          if (item.groupTag) {
            arr.push(item);
          }
        });
        for (var i = 0; i < arr.length; i++) {
          var ai = arr[i];
          if (!map[ai.groupTag]) {
            dest.push({
              groupTag: ai.groupTag,
              name: ai.groupName,
              data: [ai]
            });
            map[ai.groupTag] = ai;
          } else {
            for (var j = 0; j < dest.length; j++) {
              var dj = dest[j];
              if (dj.groupTag == ai.groupTag) {
                dj.data.push(ai);
                break;
              }
            }
          }
        }
        this.groupTag = dest
        console.log(dest);
      },
      showLinkButton(item,record){
          let btn = new ButtonExpHandler(item.exp,record);
          return btn.show;
      },
        initButtonList(){
          getAction(`${this.url.getColumns}8ac49ec7733bce48017355583fc9011e`).then((res)=>{
            console.log("--获取自定义按钮->>",res);
            if(res.success){
              this.code = res.data.code;
              this.initCgButtonList(res.data.cgButtonList);
              this.initCgEnhanceJs(res.data.enhanceJs);
              this.getGroupTag(res.data.cgButtonList);
            }else{
              this.$message.warning(res.msg)
            }
          })
        },
        initCgEnhanceJs(enhanceJs){
          //console.log("--onlineList-js增强",enhanceJs)
          if(enhanceJs){
            let Obj = eval ("(" + enhanceJs + ")");
            this.EnhanceJS = new Obj(getAction,postAction,deleteAction);
            this.cgButtonJsHandler('created')
          }else{
            this.EnhanceJS = ''
          }
        },
        initCgButtonList(btnList){
          let linkArr = []
          let buttonArr = []
          if(btnList && btnList.length>0){
            for(let i=0;i<btnList.length;i++){
              let temp = btnList[i]
              if(temp.buttonStyle=='button'){
                buttonArr.push(temp)
              }else if(temp.buttonStyle=='link'){
                linkArr.push(temp)
              }
            }
          }
          this.cgButtonLinkList = [...linkArr]
          this.cgButtonList=[...buttonArr]
          console.log("链接增强", this.cgButtonLinkList);
        },
        cgButtonJsHandler(buttonCode){
          if(this.EnhanceJS[buttonCode]){
            this.EnhanceJS[buttonCode](this)
          }
        },
        cgButtonActionHandler(buttonCode){
          //处理自定义button的 需要配置该button自定义sql
          if(!this.selectedRowKeys || this.selectedRowKeys.length==0){
            this.$message.warning("请先选中一条记录")
            return false
          }
          if(this.selectedRowKeys.length>1){
            this.$message.warning("请只选中一条记录")
            return false
          }
          let params = {
            formId:this.code,
            buttonCode:buttonCode,
            dataId:this.selectedRowKeys[0]
          }
          console.log("自定义按钮请求后台参数：",params)
          postAction(this.url.buttonAction,params).then(res=>{
            if(res.success){
              this.initDataList()
              this.$message.success("处理完成!")
            }else{
              this.$message.warning("处理失败!")
            }
          })

        },
        cgButtonLinkHandler(record,buttonCode,optType){
          if(optType=="js"){
            if(this.EnhanceJS[buttonCode]){
              this.EnhanceJS[buttonCode](this,record)
            }
          }else if(optType=="action"){
            let params = {
              formId:this.code,
              buttonCode:buttonCode,
              dataId:record.id
            }
            console.log("自定义按钮link请求后台参数：",params)
            postAction(this.url.buttonAction,params).then(res=>{
              if(res.success){
                this.initDataList()
                this.$message.success("处理完成!")
              }else{
                this.$message.warning("处理失败!")
              }
            })
          }
        },

    }
  }
  
</script>

<style  scoped>
  @import '~@assets/less/common.less';
</style>
